package com.fansmac.sc.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.AsyncRestTemplate;

import java.net.URI;


@RequestMapping("/asyncrest")
@RestController
public class AsyncRestTemplateController {

    private static  final Logger LOGGER = LoggerFactory.getLogger(AsyncRestTemplateController.class);

    @Autowired
    AsyncRestTemplate asyncRestTemplate;

    @RequestMapping(method = RequestMethod.GET)
    public String get(String content) throws Exception {
        ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate.getForEntity("http://my-provider/test?content="+content, String.class);

        future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
            @Override
            public void onSuccess(ResponseEntity<String> result) {
                LOGGER.info("======client get result : " + result.getBody());
            }

            @Override
            public void onFailure(Throwable t) {
                LOGGER.info("======client failure : " + t);
            }
        });


        HttpEntity entity = new RequestEntity(HttpMethod.POST,new URI("http://my-provider/test"));

        ListenableFuture<ResponseEntity<String>> future2 = asyncRestTemplate.postForEntity("http://my-provider/test",entity, String.class);

        future2.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
            @Override
            public void onSuccess(ResponseEntity<String> result) {
                LOGGER.info("======client get result : " + result.getBody());
            }

            @Override
            public void onFailure(Throwable t) {
                LOGGER.info("======client failure : " + t);
            }
        });


        return future.get().getBody()+"  "+future2.get().getBody();
    }
}
